<template>
  <div class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="退货单号" prop="code">
          <CodeRuleInput
            :band-value.sync="formData.code"
            table-name="sale_return_goods"
            column-name="code"
            :is-edit="id"
          />
        </el-form-item>
        <el-form-item label="制单人员">
          <el-input v-model="formData.returnName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="制单日期">
          <el-date-picker
            v-model="formData.returnTime"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            :editable="false"
          />
        </el-form-item>

        <el-form-item label="销售订单号" class="clickChoose" prop="saleOrderCode">
          <el-input v-model="formData.saleOrderCode" placeholder="请选择" readonly />
          <a
            class="clickChoose_button"
            @click.prevent="chooseOrders"
          >
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="formData.customerName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="附件" class="double">
          <FileManageFull
            :file-names="formData.fileName"
            :file-real-names="formData.fileRealName"
            :file-urls="formData.url"
            :row-index="1"
            @fileName="setFileName"
          />
        </el-form-item>
        <el-form-item v-if="saleReturnStatus == '1'" label="退货处置" class="double enterWarehouseInvoices" prop="enterWarehouseInvoices">
          <!--          <el-tooltip placement="top">-->
          <!--            <div slot="content">-->
          <!--              选择生成将在提交后自动生成入库单，如此处未生成入库单，后续可在查看页生成-->
          <!--            </div>-->
          <!--            <div>-->
          <!--              <svg-icon icon-class="提示" />-->
          <!--            </div>-->
          <!--          </el-tooltip>-->
          <div class="main_enterWarehouseInvoices">
            <el-radio v-model="formData.enterWarehouseInvoices" label="0">转质检</el-radio>
            <el-radio v-model="formData.enterWarehouseInvoices" label="1">直接入库</el-radio>
            <span class="main_enterWarehouseInvoices_text">(选择转质检将在提交后自动生成销售退货检验单，如选择直接入库，将在提交后生成入库单)</span>
          </div>
        </el-form-item>
        <el-form-item label="退货原因" class="double">
          <el-input
            v-model="formData.returnReason"
            placeholder="请输入"
            type="textarea"
            maxlength="200"
            show-word-limit
            clearable
          />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div class="formItem_header">
        <!-- 订单明细 -->
        <div />
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="addRow">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <a class="formItem_header_operate_item delete" @click="deleteRow">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>
      <div
        ref="table_container"
        class="table_container draggableTable"
      >
        <el-table
          ref="table"
          :data="listData"
          :height="tableHeight"
          stripe
          border
          row-key="id"
          style="width: 99.9%;"
          :cell-class-name="cellClassName"
          :row-class-name="rowClassName"
          :header-cell-class-name="headerCellClassName"
          @sort-change="(column)=>{sortChange(column, this)}"
          @selection-change="(val)=>{selectionChange(val, this)}"
        >
          <el-table-column type="selection" align="center" />
          <el-table-column label="本次退货数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="returnNumber" fixed="right">
            <template slot-scope="scope">
              <el-input v-model.number="scope.row.returnNumber" type="number" placeholder="请输入" clearable @input="inputNumber($event,scope.$index,scope.row)" />
            </template>
          </el-table-column>
          <!--          <el-table-column label="客户订单号" min-width="120" prop="saleCustomerOrderCode">-->
          <!--            <template slot-scope="scope">-->
          <!--              <span>{{ scope.row.saleCustomerOrderCode }}</span>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column label="客户交期" min-width="140" prop="saleCustomerDeliveryTime">
            <template slot-scope="scope">
              <span>{{ scope.row.saleCustomerDeliveryTime }}</span>
            </template>
          </el-table-column>
          <!--          <el-table-column label="客户料号" min-width="100" prop="saleCustomerMaterialCode">-->
          <!--            <template slot-scope="scope">-->
          <!--              <span>{{ scope.row.saleCustomerMaterialCode }}</span>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column label="物料编码" min-width="150" prop="materialCode" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.materialCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" min-width="100" prop="materialName" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.materialName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" min-width="100" prop="materialModel" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.materialModel }}</span>
            </template>
          </el-table-column>

          <el-table-column label="物料单位" min-width="90" prop="materialUnitName" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.materialUnitName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="orderNumber">
            <template slot-scope="scope">
              <span>{{ scope.row.orderNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="已发数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="alreadyDeliverNumber">
            <template slot-scope="scope">
              <span>{{ scope.row.alreadyDeliverNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="已退数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="actualReturnNumber">
            <template slot-scope="scope">
              <span>{{ scope.row.actualReturnNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="已入库数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="alreadyReturnNumber">
            <template slot-scope="scope">
              <span>{{ scope.row.alreadyReturnNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" width="180" prop="remark">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入" clearable />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit('0', '0')">存草稿</el-button>
      <el-button @click.stop="onSubmit('1','1')">提交</el-button>
    </div>
    <!--    <div class="main_bottom">-->
    <!--      <el-button type="cancel" @click.stop="cancel">取消</el-button>-->
    <!--      <el-button @click.stop="onSubmit('0')">保存</el-button>-->
    <!--      <el-button @click.stop="onSubmit('1')">提交</el-button>-->
    <!--    </div>-->
  </div>
</template>

<script>
import {
  addOrUpdate,
  getInfo,
  getSaleReturnStatus
} from '@/api/saleManage/saleReturn'
import { getInfoForReturn } from '@/api/saleManage/saleOrder'
import chooseOrder from './chooseOrder.vue'
import { getDictSelects } from '@/api/common/common'
import moment from 'moment'
import searchMaterial from './searchMaterial.vue'
import Big from 'big.js'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {},
    isAdd: {}
  },
  data() {
    const validateWarning = (rule, value, callback) => {
      if (!this.formData.enterWarehouseInvoices) {
        callback(new Error('是否生成入库单不能为空'))
      } else {
        callback()
      }
    }
    return {
      pageData: {
        pageNum: 1,
        pageSize: 9999,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      formData: {
        code: '',
        returnBy: '',
        returnName: '',
        returnTime: '',
        saleOrderCode: '',
        saleOrderId: '',
        customerName: '',
        returnReason: '',
        remark: '',
        fileName: '',
        fileRealName: '',
        url: '',
        saleCustomerSendInformationId: '',
        saleCustomerId: '',
        enterWarehouseInvoices: '',
        status: '',
        data: [],
        id: ''
      },
      saleReturnStatus: '',
      statusNum: '',
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      mainId: 'id',
      listData: [],
      taxRateCodeList: [],
      tableHeight: '300',
      templateSelection: '',
      tableData: [],
      peopleList: [],
      peopleData: {},
      enterMaterialCheck: '',
      isDraft: '',
      rules: {
        code: [
          { required: true, message: '退货单号不能为空', trigger: 'change' }
        ],
        saleOrderCode: [
          { required: true, message: '销售订单号不能为空', trigger: 'change' }
        ],
        enterWarehouseInvoices: [
          { required: true, validator: validateWarning, trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.formData.returnName = this.$store.state.user.name
    this.formData.returnBy = this.$store.state.user.userId
    if (!this.id) {
      // 没有id就是新增
      Object.keys(this.defaultValue).forEach((key) => {
        // 给右边数据赋值
        this.formData[key] = this.defaultValue[key]
      })
    } else {
      // 有id就是编辑
      this.getInfo()
      this.formData.id = this.id
    }
  },
  mounted() {
    this.getSaleReturnStatusInfo()
    this.formData.returnTime = moment(new Date()).format('YYYY-MM-DD')
  },
  methods: {
    getSaleReturnStatusInfo() { // 获取系统设置里销售退货单是否生成入库单的状态
      getSaleReturnStatus('saleReturnStatus').then(res => {
        this.saleReturnStatus = res.data.saleReturnStatus
        if (res.data.saleReturnStatus == '1') {
          this.formData.enterWarehouseInvoices = '0'
        } else {
          this.formData.enterWarehouseInvoices = '1'
        }
      })
    },
    setFileName(...data) {
      this.formData.fileName = data[0]
      this.formData.fileRealName = data[1]
      this.formData.url = data[2]
    },
    headerCellClassName(data) {
      if (['returnNumber'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    // // 校验整数
    inputNumber(e, index, row) {
      const num = Number(e)
      this.listData[index].returnNumber = e
      if (num >= 0 <= Number(row.alreadyDeliverNumber)) {
        this.listData[index].returnNumber = e
      } else if (num > Number(row.materialInventory)) {
        this.$message.warning('已退数量不能大于已发数量')
        this.listData[index].returnNumber = e.replace('.', '')
      }
    },
    showOrder(data) {
      console.log(data, 1111111)
      getInfoForReturn(data.id).then(res => {
        this.formData.saleCustomerId = res.data.saleCustomerId
        this.formData.customerName = res.data.customerName
        this.formData.saleOrderCode = res.data.code
        this.formData.saleOrderId = res.data.id
        if (res.data.data) {
          res.data.data.forEach(ele => {
            ele.saleOrderDetailId = ele.id
            ele.remark = ''
            // delete ele.id
            // delete ele.remark
          })
        }
        this.listData = res.data.data
        if (res.data.defaultSaleDeliverInformation) {
          this.formData.saleDeliverInformation = res.data.defaultSaleDeliverInformation
          this.formData.saleCustomerSendInformationId = res.data.defaultSaleDeliverInformation.id
        }
      })
    },
    cellClassName(data) {
      if (data.column.property == 'operate') {
        if (data.rowIndex % 2 == 0) {
          // 单数行
          return 'fixed one'
        } else {
          // 双数行
          return 'fixed two'
        }
      }
    },
    rowClassName({ row, rowIndex }) {
      if (rowIndex == this.tableData.length - 1) {
        return 'addRow'
      }
    },

    addRow() {
      if (!this.formData.saleCustomerId) {
        this.$message.warning('请选择销售订单号')
        return
      } else {
        this.$layer.iframe({
        // 弹框
          content: {
            content: searchMaterial, // 传递的组件对象
            parent: this, // 当前的vue对象
            data: {
              id: this.formData.saleOrderId,
              selectRow: this.listData
            } // props
          },
          area: ['1420px', '700px'],
          title: '选择销售退货单明细', // 标题
          shadeClose: false // 点击遮罩是否关闭
        })
      }
    },
    deleteRow() {
      this.selections.forEach(item => {
        this.listData.splice(this.listData.indexOf(item), 1)
      })
      this.selections = []
    },
    getInfo() {
      getInfo(this.id).then((res) => {
        Object.keys(this.formData).forEach((key) => {
          // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        this.isDraft = res.data.isDraft
        this.statusNum = res.data.status
        this.listData = this.formData.data
        if (!this.formData.saleDeliverInformation) {
          this.formData.saleDeliverInformation = {
            deliveryTypeLabel: '',
            consignee: '',
            phone: '',
            deliveryAddress: '',
            attentionMatters: ''
          }
        }
      })
    },
    chooseOrders() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: chooseOrder, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectionId: this.formData.saleOrderId ? this.formData.saleOrderId : ''
          } // props
        },
        area: ['1420px', '700px'],
        title: '选择销售订单号', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // 提交
    onSubmit(num, isDraft) {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.listData && this.listData.filter(item => Number(item.returnNumber) > Number(new Big(item.alreadyDeliverNumber).minus(item.actualReturnNumber).toString())).length > 0) {
            // this.$message.warning('退货数量不能大于已发数量减去已退数量')
            const obj = this.listData.filter(item => Number(item.returnNumber) > Number(new Big(item.alreadyDeliverNumber).minus(item.actualReturnNumber).toString()))[0]
            this.$message({
              message: obj.materialName + '退货数量不能大于' + Number(new Big(obj.alreadyDeliverNumber).minus(obj.actualReturnNumber).toString()),
              type: 'warning'
            })
            return
          } else if (this.listData && this.listData.filter(item => !item.returnNumber).length > 0) {
            this.$message.warning('退货数量不能为空')
            return
          } else if (this.listData && this.listData.filter(item => item.returnNumber && item.returnNumber == 0).length == 1) {
            this.$message.warning('本次退货数量不可为0')
            return
          } else if (this.listData && this.listData.filter(item => item.returnNumber && !this.SETTINGS.reg_no_zero.test(item.returnNumber)).length > 0) {
            this.$message.warning('退货数量未正确填写')
            return
          } else if (this.listData.length == 0) {
            this.$message.warning('请添加销售退货单明细')
            return
          } else {
            this.formData.data = this.$deepClone(this.listData)
            if (num == '1') {
              this.formData.returnTime = this.formData.returnTime ? moment(this.formData.returnTime).format('YYYY-MM-DD') : moment(new Date()).format('YYYY-MM-DD')
            }
            if (!this.id) {
              this.formData.data.forEach(ele => {
                ele.saleOrderDetailId = ele.id
                delete ele.id
              })
            }
            if (this.statusNum == 3 && num == 0) {
              this.statusNum = '3'
            } else {
              this.statusNum = num
            }
            if (this.saleReturnStatus == '0') {
              this.formData.enterWarehouseInvoices = '1'
            }
            addOrUpdate({ ...this.formData, status: this.statusNum, isDraft: isDraft }).then((res) => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.$layer.close(this.layerid) // 关闭弹框
              this.$parent.getList() // 调用父组件的刷新方法
            })
          }
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid) // 关闭弹框
    },

    showWayInfo(data) {
      this.formData.saleDeliverInformation.deliveryTypeLabel = data.deliveryTypeLabel
      this.formData.saleDeliverInformation.consignee = data.consignee
      this.formData.saleDeliverInformation.phone = data.phone
      this.formData.saleDeliverInformation.deliveryAddress = data.deliveryAddress
      this.formData.saleDeliverInformation.attentionMatters = data.attentionMatters
    },
    showListData(data) {
      this.listData = data
    }
    //
  }
}
</script>

<style lang="less" scoped>
.main_enterWarehouseInvoices_text {
  color: #CCCCCC;
}
.main_enterWarehouseInvoices {
  //margin-left: 50px;
}
.enterWarehouseInvoices {
  /deep/ .el-form-item__label {
    //width: 70px !important;
    padding-right: 0px !important;
  }
  /deep/ .el-tooltip {
    padding-left: 5px;
      padding-right: 40px !important;

  }
  /deep/ .el-form-item__content {
    display: flex;
  }
  /deep/ .el-radio {
    line-height: 30px
  }
}
.table_container {
  padding-bottom: 20px !important;
  padding-top: 0px !important;
}
.title {
  padding-left: 10px;
  padding-bottom: 20px;
  font-size: 24px;
  width: 100%;
}
.numberComponents {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
}
/deep/ .el-input-number.is-controls-right .el-input-number__increase {
  height: 15px;
}
.el-icon-remove {
  font-size: 25px;
  color: red;
  height: 100%;
  width: 100%;
  border: 0px;
  background-color: transparent;
}
/deep/ .el-form-item__content {
  margin-left: 0 !important;
}
/deep/ .el-form-item__label {
  text-align: right;
}
.expand_radio {
  /deep/ .el-form-item__content {
    text-align: left;
  }
}
.expand_container {
  .el-form-item {
    margin-bottom: 10px;
  }
  .expand_file {
    margin-bottom: 0px;
  }

  /deep/ .el-form-item__label {
    width: 130px !important;
  }
  /deep/ .el-form-item__content {
    width: 710px !important;
  }
}
.main_main {
  .form_padding {
    /deep/ .el-form-item {
      margin-right: 0px;
    }
    /deep/ .el-form-item__label {
      width: 120px !important;
    }
    /deep/ .el-form-item__content {
      width: 270px;
    }
    .remark {
      /deep/ .el-form-item__content {
        width: 690px !important;
        height: 60px;
        overflow-y: auto;
      }
    }
  }
}
/deep/ .el-table th.el-table__cell > .cell {
  position: unset;
}
.order_header{
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  .info_button{
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
  }
}

/deep/ .el-form-item__label {
  width: 120px !important;
}
/deep/ .el-form-item__content {
  //width: 710px !important;
}
</style>
